import * as vscode from 'vscode';
import { I18nService } from '../services/i18nService';

export class I18nCompletionProvider implements vscode.CompletionItemProvider {
    private output: vscode.OutputChannel;

    constructor(private i18nService: I18nService) {
        this.output = vscode.window.createOutputChannel('I18n Completion Debug');
    }

    public async provideCompletionItems(
        document: vscode.TextDocument,
        position: vscode.Position,
        _token: vscode.CancellationToken,
        _context: vscode.CompletionContext
    ): Promise<vscode.CompletionItem[] | vscode.CompletionList> {
        this.output.appendLine('\n[Completion Provider] Triggered');

        // Check if we're in a Python file
        if (document.languageId !== 'python') {
            this.output.appendLine('Not a Python file, returning empty list');
            return [];
        }

        // Get the current line text up to the cursor
        const linePrefix = document.lineAt(position).text.substring(0, position.character);
        this.output.appendLine(`Current line prefix: "${linePrefix}"`);

        // Check if we're in a t() call
        const tCallMatch = linePrefix.match(/t\s*\(\s*['"]([^'"]*)?$/);
        if (!tCallMatch) {
            this.output.appendLine('Not in a t() call, returning empty list');
            return [];
        }

        // Get the partial input if any
        const partialInput = tCallMatch[1] || '';
        this.output.appendLine(`Partial input: "${partialInput}"`);

        // Get all available translations
        const translations = this.i18nService.getAllTranslations();
        this.output.appendLine(`Found ${Object.keys(translations).length} translations`);

        const completionItems: vscode.CompletionItem[] = [];

        // Create completion items for each translation
        for (const [_, translation] of Object.entries(translations)) {
            const key = translation.key;
            // Filter based on partial input
            if (partialInput && !key.toLowerCase().includes(partialInput.toLowerCase())) {
                this.output.appendLine(`Skipping key "${key}" as it doesn't match partial input`);
                continue;
            }

            this.output.appendLine(`Creating completion item for key: "${key}"`);
            
            // Get the last part of the key for display
            const parts = key.split('.');
            const lastPart = parts[parts.length - 1];
            
            // Create completion item with the last part as label
            const item = new vscode.CompletionItem(lastPart, key.includes('.') ? vscode.CompletionItemKind.Value : vscode.CompletionItemKind.Module);
            
            // Set description and detail
            item.label = key;
            item.detail = `${key} - ${translation.value}`;  // Show full path in detail

            // Add more information in the documentation
            const docs = new vscode.MarkdownString();
            docs.appendCodeblock(`t("${key}")`, 'python');
            docs.appendMarkdown(`\n\nTranslation: ${translation.value}`);
            if (translation.filePath) {
                docs.appendMarkdown(`\n\nDefined in: ${translation.filePath}`);
            }
            item.documentation = docs;

            // Use full path for filtering and insertion
            item.filterText = key;  // Allow filtering by full path
            item.insertText = key;  // Insert full path
            item.preselect = true;
            item.sortText = key;  // Sort by full path

            this.output.appendLine(`Completion item created: label="${item.label}", filterText="${item.filterText}", insertText="${item.insertText}"`);

            // Add command to trigger completion again for parent nodes
            if (!key.includes('.')) {
                item.command = {
                    command: 'editor.action.triggerSuggest',
                    title: 'Re-trigger completions'
                };
            }

            completionItems.push(item);

            // If this is a nested key and matches the partial input,
            // also add its parent levels as completion items
            if (key.includes('.') && key.startsWith(partialInput)) {
                const parts = key.split('.');
                let currentPath = '';

                for (let i = 0; i < parts.length - 1; i++) {
                    currentPath = currentPath ? `${currentPath}.${parts[i]}` : parts[i];

                    // Helper function to get label text safely
                    const getLabelText = (label: string | vscode.CompletionItemLabel): string => {
                        return typeof label === 'string' ? label : label.label;
                    };

                    // Check if we already have this parent level
                    if (!completionItems.some(item => getLabelText(item.label) === parts[i])) {
                        this.output.appendLine(`Creating parent completion item for: "${currentPath}"`);
                        
                        // Create parent item with just the current part as label
                        const parentItem = new vscode.CompletionItem(parts[i], vscode.CompletionItemKind.Module);
                        parentItem.label = parts[i];
                        parentItem.detail = `${currentPath} (parent)`;
                        
                        parentItem.filterText = currentPath;
                        parentItem.insertText = currentPath;
                        parentItem.preselect = true;
                        parentItem.sortText = currentPath;
                        parentItem.command = {
                            command: 'editor.action.triggerSuggest',
                            title: 'Re-trigger completions'
                        };

                        this.output.appendLine(`Parent item created: label="${parentItem.label}", filterText="${parentItem.filterText}", insertText="${parentItem.insertText}"`);
                        
                        completionItems.push(parentItem);
                    }
                }
            }
        }

        // Sort items: parents first, then by label
        completionItems.sort((a, b) => {
            const aIsParent = a.kind === vscode.CompletionItemKind.Module;
            const bIsParent = b.kind === vscode.CompletionItemKind.Module;

            if (aIsParent !== bIsParent) {
                return aIsParent ? -1 : 1;
            }

            // Helper function to get label text safely
            const getLabelText = (label: string | vscode.CompletionItemLabel): string => {
                return typeof label === 'string' ? label : label.label;
            };

            // Compare using the extracted label text
            return getLabelText(a.label).localeCompare(getLabelText(b.label));
        });

        this.output.appendLine(`Returning ${completionItems.length} completion items`);
        return completionItems;
    }
} 